// src/store/userStore.js
import { defineStore } from "pinia";
import request from "@/utils/request";

export const useUserStore = defineStore("user", {
  state: () => ({
    userInfo: (() => {
      const raw = localStorage.getItem("userName");
      try {
        return raw ? JSON.parse(raw) : null; // 增加了对空值的检查
      } catch {
        console.warn("userName 数据格式不合法，已重置为 null");
        return null;
      }
    })(),
    token: localStorage.getItem("token") || "",

    // isLoggedIn: true, // 可选：如果需要独立状态
  }),

  getters: {
    getName: (state) => {
      console.log("getName被调用，userInfo:", state.userInfo);
      // return state.userInfo?.name || "游客";
      return state.userInfo || "游客";
      ``;
    },
    hasToken: (state) => !!state.token,
    isLoggedIn: (state) => !!state.token, // 自动推导
  },

  actions: {
    setToken(token) {
      if (token) {
        this.token = token;
        localStorage.setItem("token", token);
      }
    },

    removeToken() {
      this.token = "";
      this.userInfo = null;
      localStorage.removeItem("token");
    },

    logout() {
      this.removeToken();
    },

    setUserInfo(info) {
      this.userInfo = info;
    },

    async fetchUserInfo() {
      console.log("fetchUserInfo被调用，当前token:", this.token);
      if (!this.hasToken) return null;

      try {
        // 1. 移除多余的 params，后端通过 token 识别用户
        const res = await request.get("/api/auth/profile");

        // 2. 假设后端返回格式为 { "name": "alice" }，直接提取 name 字段
        // 若后端返回完整用户对象（如 { "id": 1, "username": "alice" }，则改为 res.username
        const realName = res.name;
        localStorage.setItem("userName", JSON.stringify(realName));

        if (!realName) {
          throw new Error("后端未返回用户名");
        }

        // 3. 用真实用户名更新 userInfo
        this.setUserInfo(realName);
        console.log("fetchUserInfo成功，userInfo更新为:", realName);
        return realName; // 返回用户名，供登录页面使用
      } catch (error) {
        console.error("获取用户信息失败:", error.message);
        // 即使失败，也保留登录时的 name，避免显示“游客”
        throw error;
      }
    },
  },
});
